// vue2.0插件写法要素：导出一个对象，有install函数，默认传入了Vue构造函数，Vue基础之上扩展
// vue3.0插件写法要素：导出一个对象，有install函数，默认传入了app应用实例，app基础之上扩展

import defaultImg from "@/assets/images/200.png";
// import XtxSkeleton from "./xtx-skeleton.vue";
// import XtxCarousel from "./xtx-carousel.vue";
// import XtxMore from "./xtx-more";
// import XtxBread from "./xtx-bread";
// import XtxBreadItem from "./xtx-bread-item";
// import XtxCheckBox from "./xtx-checkbox";
// import XtxInfiniteLoading from "./xtx-infinite-loading";
// import XtxCity from "./xtx-city";
import Message from "./Message";
import Confirm from "./Confirm";
const importFn = require.context("./", false, /\.vue$/);
export default {
  install(app) {
    // app.component(XtxSkeleton.name, XtxSkeleton);
    // app.component(XtxCarousel.name, XtxCarousel);
    // app.component(XtxMore.name, XtxMore);
    // app.component(XtxBread.name, XtxBread);
    // app.component(XtxBreadItem.name, XtxBreadItem);
    // app.component(XtxCheckBox.name, XtxCheckBox);
    // app.component(XtxInfiniteLoading.name, XtxInfiniteLoading);
    // app.component(XtxCity.name, XtxCity);

    // 批量注册全局组件
    importFn.keys().forEach((key) => {
      // 导入组件
      const component = importFn(key).default;
      // 注册组件
      app.component(component.name, component);
    });

    //指令
    defineDirective(app);
    // 挂载全局的属性   this.$message
    app.config.globalProperties.$message = Message;
    app.config.globalProperties.$confirm = Confirm;
  },
};

//定义图片懒加载指令
const defineDirective = (app) => {
  // 图片懒加载指令，使用时是v-lazy
  app.directive("lazy", {
    //mounted 组件挂在完毕后监听
    //el当前绑定的dom，binding：绑定在指令上的值
    mounted(el, binding) {
      const observer = new IntersectionObserver(
        ([{ isIntersecting }]) => {
          //当用v-lazy绑定的dom进入可视区
          if (isIntersecting) {
            observer.unobserve(el); //停止观察
            //处理图片加载出错 显示默认图片
            el.onerror = () => {
              el.src = defaultImg;
            };
            el.src = binding.value;
          }
        },
        {
          threshold: 0.01,
        }
      );
      observer.observe(el);
    },
  });
}
